// 英雄复活
import KUnit from '@kernel/util/unit'
import EventUtil from '@kernel/util/event_util'
import AbstractData from '@kernel/interfaces/AbstractData'
import KUi from '@kernel/util/ui'
import KPlayer from '@kernel/util/player'
import UI from '@data/ui'
import {GameHUD} from '@data/ui/init'
import KPlayerGroup from '@kernel/util/player_group'

const uiList: KUi[] = []

// 信息框坐标
const posList: number[] = [
  1804,
  1612.33,
  1420.67,
  1229,
]

// 排序
let sorts: string[] = []

export default class ReviveController extends AbstractData {
  private unit: KUnit;
  private ui: KUi;

  constructor(unit: KUnit) {
    super()
    this.unit = unit
    const path = UI.HeroRevive[unit.owner.id - 1]
    this.ui = KUi.searchPath(unit.owner, path)
    uiList.push(this.ui)

    EventUtil.register('UNIT_DIE', (data) => {
      if (data.__unit_id != this.unit.id) {
        return
      }
      let val = unit.getData('revive_time', 5)
      let deathCount = unit.getData('revive_count', 0)
      val += deathCount * 3;
      if (val >= 30) {
        val = 30
      }
      this.ui.parent.visible(true)
      this.refreshUI(val)
      deathCount++
      unit.setData('revive_count', deathCount)
      const timerId = setInterval(() => {
        if (val <= 0) {
          unit.revive(Fix32Vec3(0, 0, 0))
          clearInterval(timerId)
        }
        this.refreshUI(val)
        val--
      }, 1000)
    })
  }

  /**
   * 刷新ui
   * @private
   */
  private refreshUI(val: number) {
    const sort = sorts.indexOf(this.ui.id)
    if (val <= 0) {
      sorts.splice(sort, 1)
      this.ui.parent.visible(false)
      return
    }
    let pos = sorts.length
    if (sort === -1 || pos === 0) {
      sorts.push(this.ui.id)
      pos = 1
    }
    try {
      const left = this.getLeftPos(pos)
      this.ui.setText(`剩余${val}秒复活`)
      // this.ui.setPos(left, 1023.0)
      print(`剩余${val}秒复活`)
    } catch (e) {
      print(e)
    }
  }

  /**
   * 获取横向坐标
   */
  private getLeftPos(size: number): number {
    return posList[size - 1]
  }
}
